package com.qu.waibao.home.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.HomeService;
import com.qu.waibao.bean.OtherService;
import com.qu.waibao.home.adpater.CallAdapter;
import com.qu.waibao.home.adpater.HomeServiceAdapter;
import com.qu.waibao.home.adpater.TypeAdpater;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.HelpDetailActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.LogUtil;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.widget.RecyclerRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class OtherServiceActivity extends BaseActivity implements View.OnClickListener,
        BaseRecyclerAdapter.OnItemClickListener,RecyclerRefreshLayout.SuperRefreshLayoutListener{
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.tv_all)
    TextView tv_all;
    @BindView(R.id.iv_all)
    ImageView iv_all;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.iv_type)
    ImageView iv_type;
    @BindView(R.id.tv_order)
    TextView tv_order;
    @BindView(R.id.iv_order)
    ImageView iv_order;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.ll_mRoot)
    LinearLayout ll_mRoot;
    private HomeServiceAdapter adapter;
    private int flag = 0;
    private String ordertype = "";
    private String servicefrom = "2";
    private String servicecategoryid = "";
    private String state = "";
    private boolean isRefreshing = true;
    private int pageNum = 1;
    private String longitude = "";
    private String latitude = "";
    private PopupWindow popupWindow;
    private OtherService homeService;
    private List<OtherService.ServicecategoryBean> servicecategoryBean;
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            state = bundle.getString("state","");
            flag = bundle.getInt("flag",0);
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_other_service;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("其他服务");
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        int card = AppConfig.getInt("card");
        if(flag == 2){
            if(card == 2 || card == 3){
                ll_all.setVisibility(View.GONE);
                tv_title.setText("待抢单");
                iv_publish.setVisibility(View.GONE);
                state = "待抢单";
            }
        }else {
            tv_title.setText("其他服务");
            if(card == 2){
                ll_all.setVisibility(View.GONE);
                iv_publish.setVisibility(View.GONE);
            }
        }

        if(LocationUtils.Mylocation != null){
            latitude = String.valueOf(LocationUtils.Mylocation.getLatitude());
            longitude = String.valueOf(LocationUtils.Mylocation.getLongitude());
        }
        initBanner();
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new HomeServiceAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        if(adapter.getItems().size() == 0){
            mRecyclerRefreshLayout.setRefreshing(true);
            onRefreshing();
        }
    }
    @OnClick({R.id.ll_back,R.id.ll_all,R.id.ll_type,R.id.ll_order,R.id.iv_publish})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_all:
                tv_all.setTextColor(Color.parseColor("#f29f1b"));
                tv_type.setTextColor(Color.parseColor("#666666"));
                tv_order.setTextColor(Color.parseColor("#666666"));
                iv_all.setImageResource(R.drawable.hx_jiantouup);
                iv_type.setImageResource(R.drawable.jiantoudown);
                iv_order.setImageResource(R.drawable.jiantoudown);
                initPopuwindow(1,ll_mRoot);
                break;
            case R.id.ll_type:
                tv_all.setTextColor(Color.parseColor("#666666"));
                tv_type.setTextColor(Color.parseColor("#f29f1b"));
                tv_order.setTextColor(Color.parseColor("#666666"));
                iv_all.setImageResource(R.drawable.jiantoudown);
                iv_type.setImageResource(R.drawable.hx_jiantouup);
                iv_order.setImageResource(R.drawable.jiantoudown);
                initPopuwindow(2,ll_mRoot);
                break;
            case R.id.ll_order:
                tv_all.setTextColor(Color.parseColor("#666666"));
                tv_type.setTextColor(Color.parseColor("#666666"));
                tv_order.setTextColor(Color.parseColor("#f29f1b"));
                iv_all.setImageResource(R.drawable.jiantoudown);
                iv_type.setImageResource(R.drawable.jiantoudown);
                iv_order.setImageResource(R.drawable.hx_jiantouup);
                initPopuwindow(3,ll_mRoot);
                break;
            case R.id.iv_publish:
                startActivity(new Intent(this,PublishActivity.class));
                break;
        }
    }

    public void initBanner(){
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(homeService != null) {
                    String textInfoid = homeService.getBanner().get(position).getTextInfoid();
                    Intent intent = new Intent(OtherServiceActivity.this, HelpDetailActivity.class);
                    intent.putExtra("textInfoid", textInfoid);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onItemClick(int position, long itemId) {
        String serviceid = adapter.getItems().get(position).getServiceid();
        Intent intent = new Intent(this,PublishDetailActivity.class);
        intent.putExtra("serviceid",serviceid);
        startActivity(intent);
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
    }

    public class GlideImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            OtherService.BannerBean bean = (OtherService.BannerBean) path;
            Glide.with(context).load(NetManager.getFullUrl(bean.getPhoto())).into(imageView);
        }
    }

    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.service_list_get);
        map.put("userid",AppConfig.getString("userid"));
        map.put("servicecategoryid",servicecategoryid);
        map.put("servicefrom",servicefrom);
        map.put("ordertype",ordertype);
        map.put("state",state);
        map.put("latitude",latitude);
        map.put("longitude",longitude);
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
               homeService = GsonUtil.createGson().fromJson(result,OtherService.class);
               if(servicecategoryBean == null){
                   servicecategoryBean = homeService.getServicecategory();
               }
               if(homeService.getBanner().size() > 0){
                   banner.setImages(homeService.getBanner());
                   banner.start();
               }
                if (isRefreshing) {
                    adapter.clear();
                    adapter.addAll(homeService.getService());
                    if (homeService.getService().size() < 12) {
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
                    }
                } else {
                    adapter.addAll(homeService.getService());
                    if (homeService.getService().size() < 12) {
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
                    }
                    if (homeService.getService().size() == 0) {
                        pageNum--;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if(pageNum > 1){
                    pageNum--;
                    onComplate();
                }
            }

            @Override
            public void onFinished() {
                onComplate();
            }
        });
    }

    public void onComplate(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    private void initPopuwindow(int type,View mRoot){
        View view = LayoutInflater.from(this).inflate(R.layout.all_shaixuan_layout,null);
        LinearLayout ll_all = view.findViewById(R.id.ll_all);
        LinearLayout ll_type = view.findViewById(R.id.ll_type);
        LinearLayout ll_order = view.findViewById(R.id.ll_order);
        if(type == 1){
            ll_all.setVisibility(View.VISIBLE);
            ll_type.setVisibility(View.GONE);
            ll_order.setVisibility(View.GONE);
        }else if(type == 2){
            ll_all.setVisibility(View.GONE);
            ll_type.setVisibility(View.VISIBLE);
            ll_order.setVisibility(View.GONE);
        }else if(type == 3){
            ll_all.setVisibility(View.GONE);
            ll_type.setVisibility(View.GONE);
            ll_order.setVisibility(View.VISIBLE);
        }
        // 类型
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        final TypeAdpater typeAdpater = new TypeAdpater(this,BaseRecyclerAdapter.NEITHER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(typeAdpater);
        if(typeAdpater.getItems().size() == 0){
            typeAdpater.clear();
            typeAdpater.addAll(servicecategoryBean);
        }
        typeAdpater.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                servicecategoryid = typeAdpater.getItems().get(position).getServicecategoryid();
                tv_type.setText(typeAdpater.getItems().get(position).getServicecategoryname());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        // 所有
        final TextView tv_alls = view.findViewById(R.id.tv_alls);
        final TextView tv_my = view.findViewById(R.id.tv_my);
        (view.findViewById(R.id.tv_alls)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                   servicefrom = "2";
                   tv_all.setText(tv_alls.getText().toString());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        (view.findViewById(R.id.tv_my)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                servicefrom = "1";
                tv_all.setText(tv_my.getText().toString());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        //筛选
        final TextView tv_time = view.findViewById(R.id.tv_time);
        final TextView tv_money = view.findViewById(R.id.tv_money);
        final TextView tv_distance = view.findViewById(R.id.tv_distance);
        (view.findViewById(R.id.tv_time)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ordertype = "1";
                tv_order.setText(tv_time.getText().toString());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        (view.findViewById(R.id.tv_money)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ordertype = "2";
                tv_order.setText(tv_money.getText().toString());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        (view.findViewById(R.id.tv_distance)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ordertype = "3";
                tv_order.setText(tv_distance.getText().toString());
                isRefreshing = true;
                requestData();
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(mRoot);
    }


}
